﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using AbstraX.Contracts;
using AbstraX;

namespace CodeGenerationPipeline
{
    public class CodeWriter : ICodeWriter
    {
        private FileInfo fileInfo;
        private EmitDebugInfoLevel emitDebugInfoLevel;
        private StreamWriter writer;
        private static Stack<CodeWriter> writerStack = new Stack<CodeWriter>();

        public CodeWriter(FileInfo fileInfo, EmitDebugInfoLevel emitDebugInfoLevel)
        {
            this.fileInfo = fileInfo;
            this.emitDebugInfoLevel = emitDebugInfoLevel;

            var stream = fileInfo.OpenWrite();
            
            this.writer = new StreamWriter(stream);

            if (emitDebugInfoLevel != EmitDebugInfoLevel.None)
            {
                AbstraXExtensions.ShowInCommentsMode = true;
            }

            writerStack.Push(this);
        }

        public void Write(string output)
        {
            writer.Write(output);
        }

        public void Dispose()
        {
            writerStack.Pop();

            writer.Flush();
            writer.Close();

            if (emitDebugInfoLevel != EmitDebugInfoLevel.None && writerStack.Count == 0)
            {
                AbstraXExtensions.ShowInCommentsMode = false;
            }
        }
    }
}
